<template>
  <div class="app-container">
    <div class="filter-container" style="padding-bottom: 25px">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate" v-permission="'add_notify'">
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >

      <el-table-column label="ID" prop="id"  align="center" width="80" >
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="公告封面" width="110px" align="center">
        <template slot-scope="{row}">
          <img :src="row.path" alt="" style="width: 50px;height: 50px">
        </template>
      </el-table-column>


      <el-table-column label="公告标题" align="center">
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>


      <el-table-column label="公告分类" align="center">
        <template slot-scope="{row}">
          <span>{{ row.notify_classify.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="260" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary"  size="mini" @click="handleUpdate(row)" v-permission="'edit_notify'">
            编辑
          </el-button>

          <el-button  size="mini" type="danger" @click="handleModifyStatus(row)" v-permission="'delete_notify'">
            删除
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" fullscreen>

      <el-form ref="dataForm"  :model="temp" label-position="left"  >
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>

        <el-form-item label="公告分类">
          <el-select v-model="temp.pid" placeholder="请选择公告分类">
            <el-option :label="vv.name" :value="vv.id" v-for="vv in clssify"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="公告描述">
          <el-input type="textarea" v-model="temp.desc"></el-input>
        </el-form-item>

        <upload :label="'公告封面'" :old_path="temp.path" @upload-event="success"></upload>

        <el-form-item  label="内容" prop="contents" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="temp.contents" :height="400" />
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>

</template>

<script>
    import { notifyLists, notifyStore, notifyUpdate, notifyDelete,notifyGetClassify } from '@/api/notify'
    import Pagination from '@/components/Pagination' // secondary package based on el-pagination

    import Tinymce from '@/components/Tinymce'

    import Upload from '@/components/Upload'


    const defaultForm = {
        status: 'draft',
        title: '', // 文章题目
        content: '', // 文章内容
        content_short: '', // 文章摘要
        source_uri: '', // 文章外链
        image_uri: '', // 文章图片
        display_time: undefined, // 前台展示时间
        id: undefined,
        platforms: ['a-platform'],
        comment_disabled: false,
        importance: 0
    }

    export default {
        name: 'notify',
        components: { Pagination,Tinymce,Upload },

        data(){
            return {
                postForm: Object.assign({}, defaultForm),
                data: [],
                checked_keys:[],
                defaultProps: {
                    children: 'children',
                    label: 'name'
                },
                total:0,
                tableKey:0,
                listLoading: true,
                list: null,

                listQuery: {
                    page: 1,
                    limit: 20,
                    username: undefined,
                },
                importanceOptions: [1, 2, 3],
                dialogFormVisible:false,
                dialogFormVisiblePermission:false,
                rules: {
                },
                dialogStatus: '',
                textMap: {
                    update: '编辑',
                    create: '添加'
                },
                temp: {
                    type:1,
                    id: undefined,
                    title: '',
                    path:'',
                    desc:'',
                    pid:0
                },
                row:{},
                clssify:[]
            }
        },

        computed: {
            contentShortLength() {
                return this.postForm.content_short.length
            },
            displayTime: {
                // set and get is useful when the data
                // returned by the back end api is different from the front end
                // back end return => "2013-06-25 06:59:25"
                // front end need timestamp => 1372114765000
                get() {
                    return (+new Date(this.postForm.display_time))
                },
                set(val) {
                    this.postForm.display_time = new Date(val)
                }
            }
        },

        created() {
            this.getList()
        },
        methods:{
            tiao(value){
                console.log(value)
            },

            success(value){
                this.temp.path = value;
            },

            handleFilter() {
                this.listQuery.page = 1
                this.getList()
            },


            handleModifyStatus(row) {
                this.$confirm('确定删除吗', 'Warning', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(async() => {
                        await notifyDelete({id:row.id})
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        })

                        await this.getList();
                    })
                    .catch(err => {

                    })

            },
            handleUpdate(row) {
                this.temp = Object.assign({}, row) // copy obj

                this.dialogStatus = 'update'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })
            },
            getList() {
                this.listLoading = true
                notifyLists(this.listQuery).then(response => {

                    this.list = response.data.items
                    this.total = response.data.total

                    setTimeout(() => {
                        this.listLoading = false
                    }, 100)
                })


                notifyGetClassify().then(response => {

                    this.clssify = response.data;
                })



            },

            handleCreate() {
                this.resetTemp()
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })
            },
            resetTemp() {
                this.temp = {
                    type:1,
                    id: undefined,
                    name: '',
                    path:'',
                    contents:'',
                }
            },
            createData(){

                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
                        notifyStore(this.temp).then(() => {
                            // this.list.unshift(this.temp)
                            this.dialogFormVisible = false
                            this.$notify({
                                title: '',
                                message: '添加成功',
                                type: 'success',
                                duration: 2000
                            })

                            this.getList();

                        })
                    }
                })
            },
            updateData(){
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        const tempData = Object.assign({}, this.temp)

                        notifyUpdate(tempData).then(() => {

                            this.getList();

                            this.dialogFormVisible = false
                            this.$notify({
                                title: '',
                                message: '编辑成功',
                                type: 'success',
                                duration: 2000
                            })
                        })


                    }
                })
            }
        }
    }
</script>

<style lang="scss" scoped>
  @import "~@/styles/mixin.scss";

  .createPost-container {
    position: relative;

    .createPost-main-container {
      padding: 40px 45px 20px 50px;

      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;

        .postInfo-container-item {
          float: left;
        }
      }
    }
  }
</style>

